/**
 * @author tmh
 * @date 2024/9/24 19:29
 * @description
 */
public class T121买卖股票的最佳时机 {

    /**
     * 方法一会超时
     *
     * @param prices
     * @return
     */
    public int maxProfit2(int[] prices) {
        int maxPrice = 0;
        for (int i = 0; i < prices.length; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                if (prices[j] - prices[i] > 0) {
                    int price = prices[j] - prices[i];
                    maxPrice = Math.max(maxPrice, price);
                }
            }
        }
        return maxPrice;
    }

    /**
     * 方法2
     *
     * @param prices
     * @return
     */
    public int maxProfit(int[] prices) {
        /**
         * 维护卖出之前买入的最小值
         */
        int result = 0;
        int minPrice = prices[0];
        for (int price : prices) {
            //求最大利润
            result = Math.max(result, price - minPrice);
            //更新买入的最小值
            minPrice = Math.min(minPrice, price);
        }
        return result;
    }
}
